<template>
  <div class="request-tabs">
    <el-tabs v-model="activeTab" type="card">
      <!-- 检查申请标签页 -->
      <!-- <el-tab-pane label="检查申请" name="check"> -->
        <div class="check-request-tab">
          <el-card>
            <div class="header-bar">
              <el-input v-model="checkSearchForm.techName" placeholder="按项目名称查询" style="width: 200px; margin-right: 12px;" />
              <el-select v-model="checkSearchForm.techType" placeholder="按类型筛选" style="width: 150px; margin-right: 12px;">
                <el-option label="全部" value="" />
                <el-option label="检验" value="检验" />
                <el-option label="检查" value="检查" />
                <el-option label="处置" value="处置" />
              </el-select>
              <el-button type="primary" @click="handleCheckSearch">查询</el-button>
              <el-button @click="resetCheckSearch">重置</el-button>
              <el-button type="success" @click="handleCheckBatchSave">保存选中项</el-button>
            </div>
            <div class="table-wrapper">
              <div class="total-amount">选中项目金额合计: {{ checkTotalAmount }}元</div>
              <div class="register-info" v-if="checkForm.registerId">
                当前挂号ID: <span class="register-id">{{ checkForm.registerId }}</span>
              </div>
              <el-table 
                :data="medicalTechnologyData" 
                style="max-width: 1000px; width: 100%; margin-top: 18px;" 
                border
                @selection-change="handleCheckSelectionChange"
              >
                <el-table-column type="selection" width="55" />
                <el-table-column prop="id" label="ID" width="60" />
                <el-table-column prop="techCode" label="项目编码" width="100" />
                <el-table-column prop="techName" label="项目名称" />
                <el-table-column prop="techFormat" label="规格" width="100" />
                <el-table-column prop="techType" label="类型" width="80" />
                <el-table-column prop="techPrice" label="单价" width="100" />
                <el-table-column prop="priceType" label="费用类型" width="100" />
                <el-table-column prop="deptmentId" label="科室ID" width="100" />
              </el-table>
            </div>
          </el-card>

          <!-- 检查目的输入弹窗 -->
          <el-dialog title="填写检查信息" v-model="checkInfoDialogVisible" width="500px">
            <el-form :model="checkForm" label-width="120px">
              <el-form-item label="挂号ID" required>
                <el-input v-model="checkForm.registerId" disabled />
                <div class="el-form-item__help">从当前就诊信息自动获取</div>
              </el-form-item>
              <el-form-item label="检查目的" required>
                <el-input v-model="checkForm.checkInfo" type="textarea" :rows="3" placeholder="请输入检查目的" />
              </el-form-item>
              <el-form-item label="检查部位">
                <el-input v-model="checkForm.checkPosition" placeholder="请输入检查部位" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="checkForm.checkRemark" placeholder="请输入备注信息" />
              </el-form-item>
            </el-form>
            <template #footer>
              <el-button @click="checkInfoDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="confirmCheckInfo">确认提交</el-button>
            </template>
          </el-dialog>
        </div>
      <!-- </el-tab-pane> -->

    </el-tabs>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

// 路由实例
const route = useRoute()
// 当前激活的标签页
const activeTab = ref('check')

// ======================================
// 检查申请相关变量和方法
// ======================================
const medicalTechnologyData = ref([])
const originalMedicalData = ref([])
const checkSearchForm = ref({ techName: '', techType: '' })
const selectedCheckItems = ref([])
const checkForm = ref({
  registerId: '',
  checkInfo: '',
  checkPosition: '',
  checkRemark: ''
})
const checkInfoDialogVisible = ref(false)

// 检查项目总金额
const checkTotalAmount = computed(() => {
  return selectedCheckItems.value.reduce((total, item) => {
    return total + (item.techPrice || 0)
  }, 0).toFixed(2)
})

// 从路由获取挂号ID
const getRegisterIdFromRoute = () => {
  const patientId = route.query.patientId
  if (patientId) {
    checkForm.value.registerId = patientId
    disposalForm.value.registerId = patientId
    return true
  } else {
    ElMessage.warning('未从路由参数中获取到挂号ID')
    return false
  }
}

// 获取检查项目数据
const fetchMedicalTechnologies = async () => {
  try {
    const res = await request.get('/medical-technology')
    medicalTechnologyData.value = res.data || []
    originalMedicalData.value = [...medicalTechnologyData.value]
  } catch (e) {
    ElMessage.error('获取检查项目失败: ' + (e.message || '未知错误'))
  }
}

// 检查项目选择变化
const handleCheckSelectionChange = (selection) => {
  selectedCheckItems.value = selection
}

// 检查项目搜索
const handleCheckSearch = () => {
  let filteredData = [...originalMedicalData.value]
  
  if (checkSearchForm.value.techName) {
    const keyword = checkSearchForm.value.techName.toLowerCase()
    filteredData = filteredData.filter(item => 
      item.techName.toLowerCase().includes(keyword)
    )
  }
  
  if (checkSearchForm.value.techType) {
    filteredData = filteredData.filter(item => 
      item.techType === checkSearchForm.value.techType
    )
  }
  
  medicalTechnologyData.value = filteredData
}

// 重置检查项目搜索
const resetCheckSearch = () => {
  checkSearchForm.value = { techName: '', techType: '' }
  medicalTechnologyData.value = [...originalMedicalData.value]
}

// 打开检查信息弹窗
const handleCheckBatchSave = () => {
  if (!getRegisterIdFromRoute()) return
  
  if (selectedCheckItems.value.length === 0) {
    ElMessage.warning('请先选择检查项目')
    return
  }
  
  checkInfoDialogVisible.value = true
}

// 提交检查申请
const confirmCheckInfo = async () => {
  if (!checkForm.value.registerId) {
    ElMessage.warning('未获取到有效的挂号ID，请刷新页面重试')
    return
  }
  
  if (!checkForm.value.checkInfo) {
    ElMessage.warning('请输入检查目的')
    return
  }
  
  const batchData = selectedCheckItems.value.map(item => ({
    registerId: checkForm.value.registerId,
    medicalTechnologyId: item.id,
    checkInfo: checkForm.value.checkInfo,
    checkPosition: checkForm.value.checkPosition,
    checkRemark: checkForm.value.checkRemark,
    checkState: '已开立',
    techName: item.techName,
    techPrice: item.techPrice
  }))
  
  try {
    await request.post('/check-requests/batch', batchData)
    ElMessage.success(`成功添加 ${selectedCheckItems.value.length} 个检查项目`)
    checkInfoDialogVisible.value = false
    selectedCheckItems.value = []
  } catch (e) {
    ElMessage.error('保存失败: ' + (e.message || '未知错误'))
  }
}

// ======================================
// 处置申请相关变量和方法
// ======================================
const disposalTableData = ref([])
const disposalSearchForm = ref({ techName: '', techType: '' })
const disposalDialogVisible = ref(false)
const disposalDialogTitle = ref('新增处置申请')
const disposalForm = ref({
  id: null,
  registerId: '',
  medicalTechnologyId: null,
  techName: '',
  disposalInfo: '',
  disposalPosition: '',
  disposalState: '已开立',
  disposalRemark: ''
})


// 处置项目搜索
const handleDisposalSearch = () => {
  // 实际项目中应该调用后端接口进行搜索
  // 这里简化处理，直接过滤本地数据
  let filteredData = [...disposalTableData.value]
  
  if (disposalSearchForm.value.techName) {
    const keyword = disposalSearchForm.value.techName.toLowerCase()
    filteredData = filteredData.filter(item => 
      item.techName?.toLowerCase().includes(keyword)
    )
  }
  
  // 可以根据需要添加更多筛选条件
  
  disposalTableData.value = filteredData
}

// 重置处置项目搜索
const resetDisposalSearch = () => {
  disposalSearchForm.value = { techName: '', techType: '' }
  fetchDisposalRequests()
}

// 打开处置申请弹窗
const openDisposalDialog = () => {
  getRegisterIdFromRoute()
  disposalDialogTitle.value = '新增处置申请'
  disposalForm.value = {
    id: null,
    registerId: checkForm.value.registerId,
    medicalTechnologyId: null,
    techName: '',
    disposalInfo: '',
    disposalPosition: '',
    disposalState: '已开立',
    disposalRemark: ''
  }
  disposalDialogVisible.value = true
}

// 打开编辑处置申请弹窗
const openDisposalEditDialog = (row) => {
  disposalDialogTitle.value = '编辑处置申请'
  disposalForm.value = { ...row }
  disposalDialogVisible.value = true
}

// 处置项目变更
const handleDisposalTechChange = (techId) => {
  const selectedTech = medicalTechnologyData.value.find(tech => tech.id === techId)
  if (selectedTech) {
    disposalForm.value.techName = selectedTech.techName
  }
}



// 初始化
onMounted(() => {
  fetchMedicalTechnologies()
  getRegisterIdFromRoute()
})
</script>

<style scoped>
.request-tabs {
  padding: 12px;
}
.header-bar {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
}
.table-wrapper {
  max-width: 100%;
  overflow-x: auto;
}
.total-amount {
  margin-bottom: 10px;
  color: #ff5500;
  font-weight: bold;
}
.register-info {
  margin-bottom: 10px;
  font-size: 14px;
}
.register-id {
  color: #1890ff;
  font-weight: bold;
}
</style>
